package cn.easybuy.web.pre;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.easybuy.entity.User;
import cn.easybuy.service.user.UserService;
import cn.easybuy.service.user.UserServiceImpl;
import cn.easybuy.utils.SecurityUtils;

public class UserRegister extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UserRegister() {
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("action");
		if(action.equals("checkUserName")){
			String username = request.getParameter("username");
			String phone = request.getParameter("phone");
			UserService userService = new UserServiceImpl();
			boolean isExist=userService.getPhone(username, phone);
			System.out.println(isExist);
			response.getWriter().print("{\"isExist\":"+isExist+"}");
		}

	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		User user = new User();
		String userName = request.getParameter("userName");
		String loginName = request.getParameter("loginUser");
		String loginPwd = request.getParameter("loginPwd");
		int	sex = Integer.parseInt(request.getParameter("sex"));
		//判断可选项是否为空 如果不为空则赋值
		if(request.getParameter("email")!=null){
			String email = request.getParameter("email");
			user.setEmail(email);
		}
		if(request.getParameter("identityCode")!=null){
			String identityCode = request.getParameter("identityCode");
			user.setIdentityCode(identityCode);
		}
		String phone = request.getParameter("phone");
		String identityCode = request.getParameter("identityCode");
		user.setUserName(userName);
		user.setLoginName(loginName);
		user.setPassword(SecurityUtils.md5Hex3(loginPwd));
		user.setSex(sex);
		
		user.setMobile(phone);
		
		user.setType(1);
		
		UserService userService = new UserServiceImpl();
		int num = userService.registerUser(user);
		if(num>0){
			out.print("<script>");
			out.print("alert('注册成功，转向登陆页面!');");
			out.print("window.location.href='Login.jsp';");
			out.print("</script>");
		}else{
			out.print("<script>");
			out.print("alert('注册失败，未知错误!');");
			out.print("window.location.href='Regist.jsp';");
			out.print("</script>");
		}
	}
}
